package servlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import dao.DoctorsDao;
import dao.impl.DoctorsDaoImpl;
import entity.Doctors;
import utils.GetFieldUtils;
import utils.ResponseResult;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet(name = "DoctorsServlet", urlPatterns = "/bigProjects/DoctorsServlet")

public class DoctorsServlet extends HttpServlet {

    //需要参数: department ( 肛肠科,之类)
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        DoctorsDao doctorsDao = new DoctorsDaoImpl();
        resp.setContentType("application/json");
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        String department = req.getParameter("department");

        List<Doctors> list = doctorsDao.queryByDepartment(department);
        resp.getWriter().write(ResponseResult.success(list).toString());
    }


    //修改师生所处的科室    给它赋予department和 title 的
    //参数 id department title
    @Override
    protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        DoctorsDao doctorsDao = new DoctorsDaoImpl();
        resp.setContentType("application/json");
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        String str = GetFieldUtils.getRequestPayload(req);
        ObjectMapper mapper = new ObjectMapper();
        Doctors doctors = mapper.readValue(str, Doctors.class);

        int i = doctorsDao.update(doctors);
        if (i > 0) resp.getWriter().write(ResponseResult.success().toString());
        else resp.getWriter().write(ResponseResult.failure("修改医生信息失败").toString());
    }

    //查询所有医生
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        DoctorsDao doctorsDao = new DoctorsDaoImpl();
        resp.setContentType("application/json");
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");

        List<Doctors> list = doctorsDao.queryAll();
        resp.getWriter().write(ResponseResult.success(list).toString());
    }
}
